from flask import request
from flask_restx import Resource, Namespace, fields
from app.utils.auth import token_required
from app.utils.validators import validate_required_fields, validate_email, validate_phone
from app.services.department_service import DepartmentService
from . import admin_bp

# 创建部门命名空间
departments_ns = Namespace('departments', description='部门管理相关接口')

# 定义请求模型
department_create_request = departments_ns.model('DepartmentCreateRequest', {
    'name': fields.String(required=True, description='部门名称'),
    'parent_id': fields.Integer(description='父部门ID'),
    'leader': fields.String(description='部门负责人'),
    'phone': fields.String(description='联系电话'),
    'email': fields.String(description='邮箱'),
    'sort': fields.Integer(description='排序'),
    'status': fields.Boolean(description='状态'),
    'description': fields.String(description='部门描述')
})

department_update_request = departments_ns.model('DepartmentUpdateRequest', {
    'name': fields.String(description='部门名称'),
    'parent_id': fields.Integer(description='父部门ID'),
    'leader': fields.String(description='部门负责人'),
    'phone': fields.String(description='联系电话'),
    'email': fields.String(description='邮箱'),
    'sort': fields.Integer(description='排序'),
    'status': fields.Boolean(description='状态'),
    'description': fields.String(description='部门描述')
})

# Flask-RESTX兼容的响应函数
def success_response(data=None, message='操作成功', code=200):
    """成功响应格式 - Flask-RESTX兼容版本"""
    response = {
        'code': code,
        'message': message,
        'data': data
    }
    return response, code

def error_response(message='操作失败', code=400, data=None):
    """错误响应格式 - Flask-RESTX兼容版本"""
    response = {
        'code': code,
        'message': message,
        'data': data
    }
    return response, code

def paginate_response(query, page, per_page, total=None):
    """分页响应格式 - Flask-RESTX兼容版本"""
    if total is None:
        total = query.count()
    
    items = query.offset((page - 1) * per_page).limit(per_page).all()
    
    data = {
        'list': [item.to_dict() if hasattr(item, 'to_dict') else item for item in items],
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': total,
            'pages': (total + per_page - 1) // per_page
        }
    }
    
    return success_response(data)

@departments_ns.route('')
class DepartmentListAPI(Resource):
    """部门列表"""
    
    @token_required
    def get(self, current_admin):
        # 检查是否需要树形结构
        tree = request.args.get('tree', type=bool)
        if tree:
            data = DepartmentService.get_tree()
            return success_response(data)
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        keyword = request.args.get('keyword', '')
        status = request.args.get('status', type=int)
        
        if status is not None:
            status = bool(status)
        
        query, page, per_page = DepartmentService.get_list(page, per_page, keyword, status)
        return paginate_response(query, page, per_page)
    
    @departments_ns.expect(department_create_request)
    @token_required
    def post(self, current_admin):
        # 验证必填字段
        is_valid, error_msg = validate_required_fields(['name'])
        if not is_valid:
            return error_response(error_msg, 400)
        
        data = request.get_json()
        
        # 验证邮箱格式
        if data.get('email') and not validate_email(data.get('email')):
            return error_response('邮箱格式不正确', 400)
        
        # 验证手机号格式
        if data.get('phone') and not validate_phone(data.get('phone')):
            return error_response('手机号格式不正确', 400)
        
        try:
            department = DepartmentService.create(data)
            return success_response(department.to_dict(), '创建成功')
        except Exception as e:
            return error_response(f'创建失败：{str(e)}', 500)


@departments_ns.route('/<int:dept_id>')
class DepartmentDetailAPI(Resource):
    """部门详情"""
    
    @token_required
    def get(self, current_admin, dept_id):
        department = DepartmentService.get_by_id(dept_id)
        if not department:
            return error_response('部门不存在', 404)
        
        return success_response(department.to_dict())
    
    @departments_ns.expect(department_update_request)
    @token_required
    def put(self, current_admin, dept_id):
        department = DepartmentService.get_by_id(dept_id)
        if not department:
            return error_response('部门不存在', 404)
        
        data = request.get_json()
        
        # 验证邮箱格式
        if data.get('email') and not validate_email(data.get('email')):
            return error_response('邮箱格式不正确', 400)
        
        # 验证手机号格式
        if data.get('phone') and not validate_phone(data.get('phone')):
            return error_response('手机号格式不正确', 400)
        
        try:
            updated_department = DepartmentService.update(dept_id, data)
            return success_response(updated_department.to_dict(), '更新成功')
        except Exception as e:
            return error_response(f'更新失败：{str(e)}', 500)
    
    @token_required
    def delete(self, current_admin, dept_id):
        result = DepartmentService.delete(dept_id)
        if isinstance(result, tuple):
            success, message = result
            if not success:
                return error_response(message, 400)
            return success_response(message=message)
        else:
            if not result:
                return error_response('删除失败，部门不存在', 404)
            return success_response(message='删除成功')


@departments_ns.route('/options')
class DepartmentOptionsAPI(Resource):
    """部门选项数据"""
    
    @token_required
    def get(self, current_admin):
        data = DepartmentService.get_parent_options()
        return success_response(data)


# 将命名空间注册到统一的API实例
from . import api
api.add_namespace(departments_ns, path='/departments') 